package com.jzg.jcptadmin.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.KeyboardUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.InputLowerToUpper;
import com.jzg.jcptadmin.Utils.InputUtils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.Utils.ScreenUtils;
import com.jzg.jcptadmin.adpter.PlateTypeAdapter;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.PlateTypeModel;
import com.jzg.jcptadmin.presenter.PlateTypePrsenter;
import com.jzg.jcptadmin.view.CustomRippleButton;
import com.jzg.jcptadmin.view.FullyLinearLayoutManager;
import com.jzg.jcptadmin.viewinterface.PlateTypeInterface;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 请确认铭牌型号
 * Created by zealjiang on 2017/3/15 11:28.
 * Email: zealjiang@126.com
 */

public class PlateTypeActivity extends BaseActivity implements PlateTypeInterface,TextView.OnEditorActionListener{

    @Bind(R.id.title_content)
    TextView inputTopText;
    @Bind(R.id.sdv)
    SimpleDraweeView simpleDraweeView;
    @Bind(R.id.llNormal)
    LinearLayout llNormal;
    @Bind(R.id.rvPlate)
    RecyclerView rvPlate;
    @Bind(R.id.etPlate)
    EditText etPlate;
    @Bind(R.id.tvLine)
    TextView tvLine;
    @Bind(R.id.llError)
    LinearLayout llError;
    @Bind(R.id.etPlateError)
    EditText etPlateError;
    @Bind(R.id.crbNext)
    CustomRippleButton crbNext;
    @Bind(R.id.btnNextError)
    Button btnNextError;
    @Bind(R.id.rlRetry)
    RelativeLayout rlRetry;
    @Bind(R.id.crbRetry)
    CustomRippleButton crbRetry;
    @Bind(R.id.tvRetry)
    TextView tvRetry;


    private LinearLayoutManager linearLayoutManager;
    private PlateTypeAdapter adapter;
    private List<String> listPlateType;
    private PlateTypePrsenter plateTypePrsenter;
    private String sPlateType;//铭牌型号
    private CarDetails details;
    private CarDetails detailsPlateType;
    private String bigPath;
    private boolean isSelectInput = false;//是否选择了手动输入
    private int itemSelectePos = -1;
    private String vin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plate_type);
        ButterKnife.bind(this);
        inputTopText.setText("请确认铭牌型号");
        vin = getIntent().getStringExtra("vin");
        String path = getIntent().getStringExtra("path");
        bigPath = getIntent().getStringExtra("bigPath");
        details = getIntent().getParcelableExtra("details");

        //重置simpleDraweeView的高度
        ViewGroup.LayoutParams params = simpleDraweeView.getLayoutParams();
        params.width = RadioGroup.LayoutParams.MATCH_PARENT;
        params.height = ScreenUtils.getScreenWidth(this) * 9 / 16;
        simpleDraweeView.setLayoutParams(params);

        //显示小图
        if(!TextUtils.isEmpty(path)){
            simpleDraweeView.setImageURI(path);
        }

        //设置大图
        detailsPlateType = new CarDetails();
        CarDetails.CarPicListEntity carPicListEntity = new CarDetails.CarPicListEntity();
        carPicListEntity.setPathBig(bigPath);
        carPicListEntity.setItemName18("车辆铭牌");
        ArrayList<CarDetails.CarPicListEntity> carPicListEntityList = new ArrayList<>();
        carPicListEntityList.add(carPicListEntity);
        detailsPlateType.setCarPicList(carPicListEntityList);

        //铭牌列表
        listPlateType = new ArrayList<>();
        plateTypePrsenter = new PlateTypePrsenter(DataManager.getInstance());
        plateTypePrsenter.attachView(this);

        linearLayoutManager = new FullyLinearLayoutManager(this);
        rvPlate.setLayoutManager(linearLayoutManager);
        rvPlate.setNestedScrollingEnabled(false);

        adapter = new PlateTypeAdapter(this,listPlateType);
        rvPlate.setAdapter(adapter);
        adapter.setOnItemClickListener(new PlateTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                adapter.setSelectedPosition(pos);
                if(itemSelectePos==-1){
                    adapter.notifyItemChanged(pos);
                }else{
                    adapter.notifyItemChanged(pos);
                    adapter.notifyItemChanged(itemSelectePos);
                }
                itemSelectePos = pos;

                if(pos==listPlateType.size()-1){
                    etPlate.setVisibility(View.VISIBLE);
                    tvLine.setVisibility(View.VISIBLE);
                    etPlate.setFocusable(true);
                    etPlate.requestFocus();
                    isSelectInput = true;
                    KeyboardUtils.showSoftInput(PlateTypeActivity.this.getApplication(), etPlate);
                    check();
                }else {
                    isSelectInput = false;
                    sPlateType = listPlateType.get(pos);
                    if(etPlate.getVisibility()!=View.GONE){
                        etPlate.setVisibility(View.GONE);
                        tvLine.setVisibility(View.GONE);
                        etPlate.setText("");
                    }

                    check();
                }
            }
        });

        //铭牌车辆
        etPlate.setTransformationMethod(new InputLowerToUpper());
        //不能输入表情符 汉字
        InputUtils.inputRestrict(etPlate,true,true,false,false);
        //铭牌车辆
        etPlateError.setTransformationMethod(new InputLowerToUpper());
        //不能输入表情符 汉字
        InputUtils.inputRestrict(etPlateError,true,true,false,false);

        etPlate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                check();
            }
        });

        etPlateError.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                check();
            }
        });

        etPlate.setOnEditorActionListener(this);

        //网络请求
        plateTypePrsenter.getPlateTypes(vin);//"LSGJV52P84S244832"
    }

    @OnClick({R.id.sdv,R.id.crbNext,R.id.crbRetry})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sdv:
                if(TextUtils.isEmpty(bigPath)){
                    return;
                }
                Intent intent = new Intent(PlateTypeActivity.this, PhotoForNetActivity.class);
                intent.putExtra("piclists", detailsPlateType);
                intent.putExtra("position", 0);
                intent.putExtra("isZonghe", true);
                startActivity(intent);
                break;
            case R.id.crbNext:
                if(!check()){
                    return;
                }

                if(details==null){
                    finish();
                }
                intent = new Intent(this,CarTypeSelectActivity.class);
                intent.putExtra("details",details);
                intent.putExtra("vin",vin);
                intent.putExtra("plateType",sPlateType);

                startActivity(intent);
                break;
            case R.id.crbRetry:
                //网络请求
                plateTypePrsenter.getPlateTypes(vin);
                break;
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (v.getId()){
            case R.id.etPlate:
                crbNext.performClick();
                break;
        }
        return false;
    }

    private boolean check(){
        if(llNormal.getVisibility()!=View.GONE&&isSelectInput){//当前选中的是手动输入
            sPlateType = etPlate.getText().toString();
        }else if(llError.getVisibility()!=View.GONE){
            sPlateType = etPlateError.getText().toString();
        }

        if(TextUtils.isEmpty(sPlateType)){
            //MyToast.showShort("请选择或输入铭牌型号");
            crbNext.setVisibility(View.GONE);
            crbNext.setEnabled(false);
            btnNextError.setVisibility(View.VISIBLE);
            return false;
        }
        crbNext.setVisibility(View.VISIBLE);
        crbNext.setEnabled(true);
        btnNextError.setVisibility(View.GONE);
        return true;
    }

    /**
     * 请求结果为0
     */
    private void isZero(int size){
        if(size==0){
            llNormal.setVisibility(View.GONE);
            llError.setVisibility(View.VISIBLE);
            MyToast.showShort("没有找到合适的铭牌型号，请对照铭牌在下方填写");
        }else{
            llNormal.setVisibility(View.VISIBLE);
            llError.setVisibility(View.GONE);
        }
    }

    @Override
    public void success(PlateTypeModel plateTypeModel) {
        //Test plateTypeModel.setData(new ArrayList<String>());

        isZero(plateTypeModel.getData().size());
        listPlateType.clear();
        listPlateType.addAll(plateTypeModel.getData());
        if(plateTypeModel.getData().size()>0){
            listPlateType.add("以上选项均不正确，手动输入");
        }

        adapter.notifyDataSetChanged();

        rlRetry.setVisibility(View.GONE);
        etPlateError.setText("");
    }


    @Override
    public void fail(String msg) {
        rlRetry.setVisibility(View.GONE);
        llNormal.setVisibility(View.GONE);
        llError.setVisibility(View.VISIBLE);
        MyToast.showShort("没有找到合适的铭牌型号，请对照铭牌在下方填写");
    }

    @Override
    public void error(String string) {
        MyToast.showShort(string);
        llNormal.setVisibility(View.GONE);
        llError.setVisibility(View.GONE);
        rlRetry.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("details",details);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        details = savedInstanceState.getParcelable("details");
    }
}
